<script setup>
import { nextTick, reactive, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import planApi from "@/api/planApi";
import planStudentApi from "@/api/planStudentApi";
import schoolApi from "@/api/schoolApi";
import constants from "@/utils/constants";
import QrcodeVue from "qrcode.vue";
import dayjs from "dayjs";

const searchForm = ref();
const historyParams = history.state.params;
console.log(historyParams);

let plan = ref({});
const searchModel = reactive({
  planId: historyParams.planId,
  gradeId: "",
  freeTestFlag: false,
});


const printing = ref(false);
const loading = ref(false);
const printLoading = ref(false);
const printVisible = ref(false);
const showSyncNewClassesDialog = ref(false);


let schoolList = ref([]);
let gradeClassesList = ref([]);

let syncGradeClassesList = ref([]);
let syncClassesList = ref([]);
let submitSyncData = ref({});
const syncing = ref(false);

let classesList = ref([]);

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search();
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search();
  },
});

let printPagination = reactive({
  total: 0,
  current: 1,
  pageSize: 120,
  showPageSize: true,
  pageSizeOptions: [120, 320, 480, 960],
  showTotal: true,
  pageChange: (current) => {
    printPagination.current = current;
    searchPrintStudent();
  },
  pageSizeChange(size) {
    printPagination.pageSize = size;
    searchPrintStudent();
  },
});


const columns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 200,
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
  },
  {
    title: "性别",
    slotName: "sex",
    width: 100,
  },
  {
    title: "年级",
    dataIndex: "gradeName",
    width: 100,
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 150,
  },
  {
    title: "出生日期",
    dataIndex: "birthday",
    width: 120,
  },
  {
    title: "民族",
    slotName: "nation",
    width: 100,
  },
  {
    title: "身份证号",
    dataIndex: "idNumber",
    width: 200,
  },
  {
    title: "IC卡号",
    dataIndex: "cardNo",
    width: 150,
  },
  {
    title: "学生来源",
    dataIndex: "fromSource",
    width: 100,
  },
  {
    title: "家庭地址",
    dataIndex: "address",
    width: 200,
  },
  {
    title: "录入时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const data = ref([]);
const printStudentList = ref([]);

const schoolSelectChange = (schoolId) => {
  if (schoolId) {
    planApi
      .getGradeClassesList({
        planId: historyParams.planId,
        schoolId: schoolId,
      })
      .then((res) => {
        gradeClassesList.value = res;
      });
  } else {
    gradeClassesList.value = [];
    classesList.value = [];
    searchModel.classesId = "";
    searchModel.gradeId = "";
  }
};

const changeSyncSelectSchool = (schoolId) => {
  schoolApi
    .getGradeClassesList({
      schoolId: schoolId,
    })
    .then((res) => {
      syncGradeClassesList.value = res;
    });
}

const queryGradeClassesList = (schoolId) => {
  schoolApi
    .getGradeClassesList({
      schoolId: schoolId,
    })
    .then((res) => {
      syncGradeClassesList.value = res;
    });
}

const changeSyncSelectGrade = (gradeId) => {
  let gradeModel = syncGradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (gradeModel && gradeModel.classesList && gradeModel.classesList.length > 0) {
    syncClassesList.value = gradeModel.classesList;
  } else {
    submitSyncData.classesId = "";
    syncClassesList.value = [];
  }
};

const batchUpdating = ref(false)
const batchUpdateStudentData = () => {
  batchUpdating.value = true;
  planApi.batchUpdateStudentData(searchModel).then((res) => {
    Message.success("操作成功");
    search();
    batchUpdating.value = false;
  }).catch(err => {
    batchUpdating.value = false;
  });
};

const syncInsertStudentData = () => {
  planApi.syncInsertStudentData(searchModel).then((res) => {
    Message.success("操作成功");
    search();
  });
};

const submitSyncRequest = (values) => {
  values.planId = historyParams.planId;
  if (submitSyncData.value.classesIds.length == 0) {
    Message.success("请先选择班级再同步数据");
    return;
  }
  values.classesIds = submitSyncData.value.classesIds;
  syncing.value = true;

  planApi.syncNewClassesStudentData(values).then((res) => {
    Message.success("成功新增" + res + "名学生!");
    syncing.value = false;
    showSyncNewClassesDialog.value = false;
    search();
  });
}

const deleteRecord = (record) => {
  planApi
    .deleteStudent({
      id: record.id,
    })
    .then((res) => {
      search();
    });
};

const printAdmissionTicket = () => {
  printVisible.value = true;
  searchPrintStudent(1, 120);
};

const changeSelectGrade = (gradeId) => {
  let gradeModel = gradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (gradeModel && gradeModel.children && gradeModel.children.length > 0) {
    classesList.value = gradeModel.children;
  } else {
    searchModel.classesCode = "";
    classesList.value = [];
  }
};

const getSchoolList = () => {
  planApi
    .getSchoolList({
      planId: historyParams.planId,
    })
    .then((res) => {
      schoolList.value = res;
    });
};


const managerSchoolList = ref([]);
const getManagerSchoolList = () => {
  schoolApi
    .querySchoolList({})
    .then((res) => {
      managerSchoolList.value = res;
    });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  planApi.pageStudent(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const queryPlanDetailById = () => {
  planApi.detailById({ planId: historyParams.planId }).then((resp) => {
    plan.value = resp;
  });
}

const schoolData = ref([]);
const getSchoolGradeClassesList = () => {
  loadClassesData.value = true;
  schoolApi.getSchoolGradeClassesList().then((res) => {
    schoolData.value = res;
    loadClassesData.value = false;
  });
};

const getRelationClassesList = () => {

  planApi.getRelationClassesList({
    planId: historyParams.planId
  }).then(res => {
    submitSyncData.value.classesIds = res;
  })
}

const loadClassesData = ref(false);
const syncNewClassesStudentData = () => {
  showSyncNewClassesDialog.value = true;
  nextTick(() => {
    getSchoolGradeClassesList();
    getRelationClassesList();
  })
}

const searchPrintStudent = () => {
  var params = {
    pageNo: printPagination.current,
    pageSize: printPagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  printLoading.value = true;
  planApi.pageStudent(params).then((res) => {
    printStudentList.value = res.records;
    printPagination.total = res.total;
    printLoading.value = false;
  });
};


const getNationName = (value) => {
  let nationItem = constants.nationList.find((res) => {
    return res.value == value;
  });
  return !nationItem ? "" : nationItem.label;
};

const reset = () => {
  searchForm.value.resetFields();
  searchModel.classesId = "";
  searchModel.gradeId = "";
};

const printExamTicket = () => {
  printing.value = true;
  planApi.exportForPrintExamTicket(searchModel).then(res => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName =
      "准考证-" + dayjs().format("YYYYMMDDHHmmss") + ".zip";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    printing.value = false;
  })
}

const updateInfoing = ref(false);
const updateStudentInfo = () => {
  updateInfoing.value = true;
  planApi.updateStudentInfo({
    id: historyParams.planId
  }).then(res => {
    updateInfoing.value = false;
    search();
  })
}

const exportStudenting = ref(false);
const exportStudents = () => {
  exportStudenting.value = true;
  planStudentApi.exportPlanStudent(searchModel).then(res => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName = dayjs().format("YYYYMMDDHHmmss") + ".xlsx";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    exportStudenting.value = false;
  }).catch(err => {
    exportStudenting.value = false;
  })
}


queryPlanDetailById();
search();
getSchoolList();
getManagerSchoolList();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>体测管理</a-breadcrumb-item>
        <a-breadcrumb-item>考生管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 8 }" :wrapper-col-props="{ span: 16 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="schoolId" label="学校">
                  <a-select v-model="searchModel.schoolId" placeholder="请选择学校" allow-clear @change="schoolSelectChange">
                    <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                      :label="school.name"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="gradeId" label="年级/班级">
                  <a-space>
                    <a-select style="width: 120px" v-model="searchModel.gradeId" @change="changeSelectGrade"
                      placeholder="年级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="item in gradeClassesList" :key="item.id" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                    <a-select style="width: 120px" v-model="searchModel.classesCode" placeholder="班级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="classes in classesList" :key="classes.code" :value="classes.code">{{ classes.name
                        }}</a-option>
                    </a-select>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" label="学生姓名">
                  <a-input v-model="searchModel.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="sex" label="性别">
                  <a-select v-model="searchModel.sex" placeholder="请选择性别">
                    <a-option value="1">男</a-option>
                    <a-option value="2">女</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="studyCode" label="学籍号">
                  <a-input v-model="searchModel.studyCode" placeholder="请输入学籍号" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-card>
        <div class="toolbar">
          <a-space>
            <a-button type="primary" :loading="batchUpdating" @click="batchUpdateStudentData">
              <template #icon>
                <icon-refresh />
              </template>
              批量更新学生数据
            </a-button>
            <!-- <a-tooltip v-if="plan.parentId == 0" content="选择上方学校才可操作">
              <a-button :disabled="!searchModel.schoolId" type="outline" @click="syncInsertStudentData">
                <template #icon>
                  <icon-refresh />
                </template>
                同步新增学生
              </a-button>
            </a-tooltip> -->
            <!-- <a-button type="outline" @click="syncNewClassesStudentData">
              <template #icon>
                <icon-rotate-right />
              </template>
              同步新增学生
            </a-button> -->
            <a-popconfirm content="确认导出所有查询数据的准考证吗？" @ok="printExamTicket">
              <a-button type="outline" :loading="printing">
                <template #icon>
                  <icon-printer />
                </template>
                {{ printing ? '正在导出...' : '导出准考证' }}
              </a-button>
            </a-popconfirm>
            <a-button type="outline" @click="exportStudents" :loading="exportStudenting">
              <template #icon>
                <icon-download />
              </template>
              {{ exportStudenting ? '正在导出...' : '导出考生信息' }}
            </a-button>
            <!-- <a-popconfirm content="确认更新该计划里所有的考生信息吗？" @ok="updateStudentInfo">
              <a-button :loading="updateInfoing" type="outline">
                <template #icon>
                  <icon-rotate-right />
                </template>
                更新考生信息
              </a-button>
            </a-popconfirm> -->

          </a-space>
        </div>
        <a-table :columns="columns" :loading="loading" :data="data" @page-change="pagination.pageChange"
          @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">
          <template #nation="{ record }">
            {{ getNationName(record.nation) }}
          </template>
          <template #sex="{ record }">
            {{ record.sex == "1" ? "男" : " 女" }}
          </template>
          <template #action="{ record }">
            <a-space>
              <a-popconfirm content="确认要删除该数据吗？" @ok="deleteRecord(record)">
                <a-button type="text">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-card>

    </a-card>
  </div>
  <a-modal v-model:visible="showSyncNewClassesDialog" @ok="submitSyncRequest" width="600px" title="选择需要同步数据的班级">
    <a-card style="width: 100%">
      <a-spin :loading="loadClassesData" tip="正在加载中..." style="width: 100%;height: 550px;">
        <div style="height: 550px;overflow: auto;">
          <a-tree :checkable="true" v-model:checked-keys="submitSyncData.classesIds" blockNode checked-strategy="child"
            :fieldNames="{ key: 'id', title: 'name' }" :data="schoolData">
          </a-tree>
        </div>
      </a-spin>
    </a-card>
    <!--<a-form :model="submitSyncData" @submit-success="submitSyncRequest">
      <a-form-item label="">
      </a-form-item>
       <a-form-item field="schoolId" label="学校" :rules="[{ required: true, message: '请选择学校' }]">
        <a-select v-model="submitSyncData.schoolId" placeholder="学校" @change="changeSyncSelectSchool">
          <a-option v-for="item in managerSchoolList" :key="item.id" :value="item.id">{{ item.name
            }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="gradeId" label="年级" :rules="[{ required: true, message: '请选择年级' }]">
        <a-select v-model="submitSyncData.gradeId" @change="changeSyncSelectGrade" placeholder="年级">
          <a-option v-for="item in syncGradeClassesList" :key="item.id" :value="item.id">{{ item.name
            }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="classesId" label="班级" :rules="[{ required: true, message: '请选择班级' }]">
        <a-select v-model="submitSyncData.classesId" placeholder="班级">
          <a-option v-for="classes in syncClassesList" :key="classes.id" :value="classes.id">{{ classes.name
            }}</a-option>
        </a-select>
      </a-form-item> 
      <a-form-item>
        <a-button type="primary" html-type="submit" :loading="syncing">{{ syncing ? '正在同步...' : '开始同步' }}</a-button>
      </a-form-item>
    </a-form>-->
  </a-modal>
  <a-drawer title="打印准考证" :width="900" v-model:visible="printVisible" :destroy-on-close="true"
    :footer-style="{ textAlign: 'right' }" :bodyStyle="{ 'padding-top': '0px' }">
    <div id="printCon" style="width: 210mm; padding: 0 10px">
      <div>
        <div v-for="(std, index) in printStudentList" :key="std.studyCode" :span="12" style="
            width: 49%;
            float: left;
            margin-top: 10px;
            height: 370px;
            padding: 0 0.5%;
          ">
          <div class="print-item" style="
              background-color: #fff;
              border: 1px solid #000000;
              padding: 10px 16px;
            ">
            <div class="title" style="font-size: 20px; font-weight: bold; text-align: center">
              准考证
            </div>
            <div class="info" style="display: flex; position: relative">
              <div class="flex1 info-up-con" style="flex: 1">
                <div class="info-item" style="font-size: 16px; height: 20px; line-height: 20px">
                  <span class="label" style="width: 90px; display: inline-block; font-weight: 600">姓名：</span><span>{{
                    std.name }}</span>
                </div>
                <div class="info-item" style="font-size: 16px; height: 20px; line-height: 20px">
                  <span class="label" style="width: 90px; display: inline-block; font-weight: 600">性别：</span><span>{{
                    std.sex == 1 ? "男" : "女" }}</span>
                </div>
                <div class="info-item" style="font-size: 16px; height: 20px; line-height: 20px">
                  <span class="label" style="width: 90px; display: inline-block; font-weight: 600">学校名称：</span><span>{{
                    std.schoolName }}</span>
                </div>
                <div class="info-item" style="font-size: 16px; height: 20px; line-height: 20px">
                  <span class="label" style="width: 90px; display: inline-block; font-weight: 600">年级班级：</span><span>{{
                    std.gradeName + " " + std.classesName }}</span>
                </div>
              </div>
              <div class="qr">
                <qrcode-vue :value="std.studyCode" :size="80" level="H" />
              </div>
            </div>
            <div class="info">
              <div class="flex1 info-up-con">
                <div class="info-item" style="font-size: 16px; height: 20px; line-height: 20px">
                  <span class="label" style="width: 90px; display: inline-block; font-weight: 600">学籍号：</span><span>{{
                    std.studyCode }}</span>
                </div>
                <div class="info-item" style="font-size: 16px; height: 20px; line-height: 20px">
                  <span class="label"
                    style="width: 90px; display: inline-block; font-weight: 600">考试项目：</span><span></span>
                </div>
              </div>
            </div>
            <div class="test-result" style="margin-top: 10px">
              <table class="table" style="width: 100%; border: 1px solid #000000">
                <tbody>
                  <tr v-if="std.testPrjNames && std.testPrjNames.length > 0" style="border-bottom: 1px solid #000000">
                    <td v-for="idx in 4" :key="idx" style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      ">
                      {{
                        !std.testPrjNames[idx - 1]
                          ? ""
                          : std.testPrjNames[idx - 1]
                      }}
                    </td>
                  </tr>
                  <tr v-if="std.testPrjNames && std.testPrjNames.length > 0" style="border-bottom: 1px solid #000000">
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                  </tr>
                  <tr v-if="std.testPrjNames && std.testPrjNames.length > 0" style="border-bottom: 1px solid #000000">
                    <td v-for="idx in 4" :key="idx + 3" style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      ">
                      {{
                        !std.testPrjNames[idx + 3]
                          ? ""
                          : std.testPrjNames[idx + 3]
                      }}
                    </td>
                  </tr>
                  <tr style="border-bottom: 1px solid #000000">
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                    <td style="
                        text-align: center;
                        width: 100px;
                        height: 28px;
                        font-size: 12px;
                        border-right: 1px solid #000000;
                      "></td>
                  </tr>
                </tbody>
              </table>
              <div>
                <div style="font-weight: 500; margin-top: 10px">注意事项</div>
                <div style="margin: 10px 0">
                  避免准考证二维码磨损或者弯折破损
                </div>
              </div>
            </div>
          </div>
          <div v-if="(index + 1) % 6 == 0" style="page-break-after: always"></div>
        </div>
      </div>
    </div>
    <template #footer>
      <div style="float: left">
        <a-pagination :page-size-options="printPagination.pageSizeOptions" :page-size="printPagination.pageSize"
          :total="printPagination.total" :current="printPagination.current" @change="printPagination.pageChange"
          @page-size-change="printPagination.pageSizeChange" show-page-size show-jumper />
      </div>
      <a-button style="margin-right: 8px" @click="printVisible = false">关闭</a-button>
      <a-button type="primary" @click="printExamTicket" :loading="printing">{{ printing ? '正在导出...' :
        '导出准考证' }}</a-button>
    </template>
  </a-drawer>

</template>

<style>
@page {
  size: auto;
  margin: 0mm;
}
</style>
